#include "ArpScanner.h"
#include <winsock2.h>
#include <winsock.h>
#include <iphlpapi.h>

ARPScanner::ARPScanner()
{
}

void ARPScanner::SendARP(unsigned long DestIP, unsigned long SrcIP)
{
    char output[256] = {0};
    ULONG ulLen = 6;
    BYTE* bPhysAddr;
    unsigned long pulMac[2];
	DWORD dwRetVal = ::SendARP(DestIP, SrcIP, &pulMac, &ulLen);
    if (dwRetVal == NO_ERROR)
    {
        bPhysAddr = (BYTE*)&pulMac;
        if (ulLen) 
        {
            int offset = 0;
            for (int i = 0; i < (int)ulLen; i++) 
            {
                if (i == (int)(ulLen - 1))
                    offset += sprintf(output + offset, "%.2X\0", (int)bPhysAddr[i]);
                else
                    offset += sprintf(output + offset, "%.2X-", (int)bPhysAddr[i]);
            }
        }
        else
        {
            printf("Warning: SendArp completed successfully, but returned length=0\n");
        }

        struct in_addr network;
        network.s_addr=DestIP;    //为s_addr赋值--网络字节序
        OnSucceeded.Broadcast(inet_ntoa(network), output);
    }
    else
    {
        OnFailed.Broadcast();

        printf("Error: SendArp failed with error: %d", dwRetVal);
        switch (dwRetVal) {
        case ERROR_GEN_FAILURE:
            printf(" (ERROR_GEN_FAILURE)\n");
            break;
        case ERROR_INVALID_PARAMETER:
            printf(" (ERROR_INVALID_PARAMETER)\n");
            break;
        case ERROR_INVALID_USER_BUFFER:
            printf(" (ERROR_INVALID_USER_BUFFER)\n");
            break;
        case ERROR_BAD_NET_NAME:
            printf(" (ERROR_GEN_FAILURE)\n");
            break;
        case ERROR_BUFFER_OVERFLOW:
            printf(" (ERROR_BUFFER_OVERFLOW)\n");
            break;
        case ERROR_NOT_FOUND:
            printf(" (ERROR_NOT_FOUND)\n");
            break;
        default:
            printf("\n");
            break;
        }
    }
}

void ARPScanner::SendARP(const char* DestIP)
{
    SendARP(inet_addr(DestIP));
}
